package com.reggie.task;

import com.reggie.entity.Orders;
import com.reggie.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cglib.core.Local;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


@Component
@Slf4j
public class OrderTask {

    //计时任务
    @Autowired
    private OrderMapper orderMapper;


    //处理超时订单
    @Scheduled(cron = "0 0/1 * * * ?")  //处理超时订单 每隔1分钟执行一次
    public void processTimeoutOrder() {
        //获取用户下单时间 之后的15分钟的时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //获取当前时间过去15分钟之后的订单信息
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, time);
        if (ordersList != null && ordersList.size() > 0) {
            //15分钟之后 订单还存在
            ordersList.forEach(orders -> {
                //重新设置订单状态
                orders.setStatus(Orders.CANCELLED);
                //返回订单取消原因
                orders.setCancelReason("支付超时,自动取消");
                //将修改后的订单Ordes 调用方法修改数据库的订单内容
                orderMapper.updateOrdersById(orders);

            });
        }


    }

    //处理派送超时订单
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeiveryOrder() {
        //一个小时之后
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        if (ordersList != null && ordersList.size() > 0) {
            //15分钟之后 订单还存在
            ordersList.forEach(orders -> {
                //重新设置订单状态
                orders.setStatus(Orders.COMPLETED);
                orderMapper.updateOrdersById(orders);

            });


        }
    }
}
